import 'package:dio/dio.dart' as dio;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:glorysoft_mobile_plugin/tool/utils/directory_util.dart';
import 'package:open_file/open_file.dart';

class ProgressDialogController extends GetxController {
  double value = 0;
  String url = "";

  downloadApk() async {
    setInitDir(initStorageDir: true);
    await DirectoryUtil.getInstance();
    String? path = DirectoryUtil.getStoragePath(
        category: 'AppDownload', fileName: 'NewApp.apk');
    dio.Dio dioss = dio.Dio();
    try{
      dio.Response response =
      await dioss.download(url, path, onReceiveProgress: (received, total) {
        if (received == total) {
          value = 1;
          update();
          Get.back();
          OpenFile.open(path);
        } else {
          value = received / total;
          update();
        }
      });
    } on dio.DioError catch(e){
      Get.back();
      Fluttertoast.showToast(
        msg: e.message+"-下载失败请重试!",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
      );
    }
  }
}
